const { resolve } = require('path')
const fse = require('fs-extra')

// 拿到 blob 的路径
const UPLOAD_DIR = resolve(__dirname, '.', 'target')
// 等会要存的路径和文件名字
const filename = 'weather_son'
const filePath = resolve(UPLOAD_DIR, '..', `${filename}.png`)

const mergeFileChunk = async (filePath, filename, size) => {
  // console.log(filePath, filename, size);
  // console.log(chunkDir); 拿到target/weather_son
  const chunkDir = resolve(UPLOAD_DIR, filename)
  const chunkPaths = await fse.readdir(chunkDir)
  chunkPaths.sort((a, b) => a.split('-')[1] - b.split('-')[1])
  await Promise.all(
    chunkPaths.map((chunkPath, index) => {
      return pipeStream(
        // 拿到每一个weather_son-0
        resolve(chunkDir, chunkPath),
        fse.createWriteStream(filePath, {
          start: index * size,
          end: (index + 1) * size
        }
        )
      )
    })
  )
  // console.log('文件合并成功')
  fse.rmdirSync(chunkDir);
}
const pipeStream = (path, writeStream) => {
  // path 每一个weather_son分块
  // writeStream 创建的新文件
  return new Promise(resolve => {
    const readStream = fse.createReadStream(path)
    readStream.on('end', _ => {
      fse.unlinkSync(path)
      resolve()
    })
    readStream.pipe(writeStream)
  })
}
mergeFileChunk(filePath, filename, 1024*1024)